package utils

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
	"sync/atomic"
	"time"
)

// CharNum 统计字符数
func CharNum(str string) int {
	cnt := 0
	for range str {
		cnt++
	}
	return cnt
}

func CostTimeOfFunc(fn func()) time.Duration {
	startTime := time.Now()
	fn()
	endTime := time.Now()
	costTime := endTime.Sub(startTime)
	// fmt.Println("costTime:", costTime)
	return costTime
}

func ClearConsole() {
	cmd := exec.Command("clear")
	cmd.Stdout = os.Stdout
	err := cmd.Run()
	if err != nil {
		panic(err)
	}
}

var IncreaseID int64 = 0

// 雪花算法生成唯一ID
func GetSnowflakeID(machineID int64) string {
	// 1bit| 41bit时间戳 |10bit机器号|12bit序列递增|
	now := time.Now().UnixNano()
	id := int64(0)
	id = id | (GetInt64LowNBits(now, 41) << 22)
	id = id | (GetInt64LowNBits(machineID, 10) << 12)
	id = id | GetInt64LowNBits(IncreaseID, 12)
	atomic.AddInt64(&IncreaseID, 1)
	return fmt.Sprintf("%X", id)
}

func GetInt64LowNBits(num int64, n int) int64 {
	return num & (1<<n - 1)
}

// ClearDir 清空文件夹
func ClearDir(dirPath string) {
	err := os.RemoveAll(dirPath) // 如果dirPath不存在，不会报错
	if err != nil {
		panic(err)
	}
	err = os.MkdirAll(dirPath, os.ModePerm)
	if err != nil {
		panic(err)
	}
}

// RemoveDuplicatesAndCount 去除string数组重复元素并统计频率
func RemoveDuplicatesAndCount(strs []string) map[string]int {
	// 使用 map 来记录出现的频率
	frequency := make(map[string]int)
	for _, str := range strs {
		str = strings.ToLower(str)
		frequency[str]++
	}
	return frequency
}
